<template>
  <div class="my-applications">
    <div class="page-card">
      <!-- <div style="margin-left: 20px;font-weight: bold;color: rgb(66,66,100);">
        我的应用
      </div>
      <el-divider /> -->
      
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <!-- 筛选标题和搜索 -->
        <div class="filter-header">
          <div>
            <h3 class="filter-title">全部应用</h3>
          </div>
          <div class="search-section-right">
            <el-input
              v-model="searchQuery"
              placeholder="从全部应用中搜索"
              @input="handleSearch"
              clearable
              class="search-input-el"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <button class="btn-create-new" @click="createNewApp">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <line x1="12" y1="5" x2="12" y2="19"></line>
                <line x1="5" y1="12" x2="19" y2="12"></line>
              </svg>
              创建新应用
            </button>
          </div>
        </div>
      </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载应用列表...</p>
    </div>

      <!-- 应用卡片网格 -->
      <div v-else-if="filteredApplications.length > 0" class="applications-grid">
        <div 
          v-for="app in filteredApplications" 
          :key="app.id"
          class="app-card"
        >
          <!-- 卡片头部：图标 + 标题 + 状态 -->
          <div class="card-header">
            <!-- 左侧图标 -->
            <!-- <div class="app-icon">
              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                <circle cx="9" cy="9" r="2"></circle>
                <path d="M21 15.5c-1.5-1.5-4-1.5-5.5 0"></path>
                <path d="M14 21.5c-1.5-1.5-4-1.5-5.5 0"></path>
              </svg>
            </div> -->
            
            <!-- 右侧内容区 -->
            <div class="header-content">
              <!-- 标题行 -->
              <div class="title-row">
                <h3 class="app-name">{{ app.name }}</h3>
                <div class="status-area">
                  <span v-if="app.status === 'active'" class="status-badge status-active">运行中</span>
                  <span v-else class="status-badge status-inactive">已停止</span>
                </div>
              </div>
              
              <!-- 标签行 -->
              <div class="tags-row" v-if="app.category">
                <span class="tag-item">{{ app.category }}</span>
              </div>
            </div>
          </div>
          
          <!-- 描述区域 -->
          <div class="card-description">
            <p class="app-description">{{ app.description }}</p>
          </div>
          
          <!-- 分类和更新时间 -->
          <div class="card-meta">
            <div class="meta-left">
              <span class="category-label">{{ app.category }}</span>
            </div>
            <div class="meta-right">
              <span class="update-time">{{ formatDate(app.createTime) }}创建</span>
            </div>
          </div>
          
          <!-- 分割线 -->
          <div class="divider"></div>
          
          <!-- 操作按钮 -->
          <div class="app-actions">
            <div class="action-item" @click="viewAppDetail(app)">
              <el-icon class="action-icon">
                <View />
              </el-icon>
              <span class="action-text">查看详情</span>
            </div>
            <div class="action-item" @click="openManualUpload(app)" v-if="app.category === '手动' || app.category === '全部'">
              <el-icon class="action-icon">
                <Upload />
              </el-icon>
              <span class="action-text">手动识别</span>
            </div>
            <div class="action-item action-danger" @click="deleteApp(app)">
              <el-icon class="action-icon">
                <Delete />
              </el-icon>
              <span class="action-text">删除应用</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <div class="empty-icon">
          <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
            <circle cx="9" cy="9" r="2"></circle>
            <path d="M21 15.5c-1.5-1.5-4-1.5-5.5 0"></path>
            <path d="M14 21.5c-1.5-1.5-4-1.5-5.5 0"></path>
          </svg>
        </div>
        <h3>还没有应用</h3>
        <p>开始创建您的第一个象差推理应用吧</p>
        <button class="btn-create-first" @click="createNewApp">创建应用</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getToken } from '@/utils/auth'
import appAPI from '@/api/agriculture/xctl/appManage'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, View, Delete, Upload } from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const loading = ref(false)
const applications = ref([])

// 模拟应用数据
const mockApplications = [
  {
    id: 1,
    name: '农作物病害检测应用',
    description: '基于AI技术的农作物病害智能识别系统，帮助农户及时发现和处理作物病害问题。',
    serviceName: '病害识别API',
    category: '农业应用',
    status: 'active',
    createTime: '2024-01-15T10:30:00Z',
    isPublic: true
  },
  {
    id: 2,
    name: '虫害监测系统',
    description: '实时监测农田虫害情况，提供预警和防治建议。',
    serviceName: '虫害识别API',
    category: '监控应用',
    status: 'inactive',
    createTime: '2024-01-10T14:20:00Z',
    isPublic: false
  },
  {
    id: 3,
    name: '作物长势分析',
    description: '分析作物生长状况，提供科学的种植建议和优化方案。',
    serviceName: '长势识别API',
    category: '分析应用',
    status: 'active',
    createTime: '2024-01-08T09:15:00Z',
    isPublic: true
  }
]

// 获取应用列表
const fetchApplications = async () => {
  try {
    loading.value = true
    
    const token = getToken()
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
     const response = await fetch(`${baseURL}/customer/appManage/list`, {
       headers: {
         'Authorization': `Bearer ${token}`
       }
     })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    
    if (result.code === 200) {
      // 映射后端数据结构到前端期望的格式
      const rawData = result.rows || result.data || []
      applications.value = rawData.map(item => ({
        id: item.appId,
        name: item.appName,
        description: item.appDescription || '暂无描述',
        serviceName: item.appType || '其他服务',
        category: item.appType || '未分类',
        status: item.status === '0' ? 'active' : 'inactive',
        createTime: item.createTime,
        isPublic: true,
        apiKey: item.apiKey,
        secretKey: item.secretKey,
        appUser: item.appUser
      }))
    } else {
      console.error('获取应用列表失败:', result.message)
      // 如果API调用失败，使用模拟数据作为备选
      applications.value = mockApplications
    }
  } catch (error) {
    console.error('获取应用列表失败:', error)
    // 网络错误时使用模拟数据
    applications.value = mockApplications
  } finally {
    loading.value = false
  }
}

// 计算属性：过滤后的应用
const filteredApplications = computed(() => {
  if (!searchQuery.value.trim()) {
    return applications.value
  }
  
  const query = searchQuery.value.toLowerCase()
  return applications.value.filter(app => 
    (app.name || '').toLowerCase().includes(query) ||
    (app.description || '').toLowerCase().includes(query) ||
    (app.serviceName || '').toLowerCase().includes(query) ||
    (app.category || '').toLowerCase().includes(query)
  )
})

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// 创建新应用
const createNewApp = () => {
  router.push('/agricultureXctl/create-app')
}

// 查看应用详情
const viewAppDetail = async (app) => {
  try {
    const response = await appAPI.getAppDetail(app.id)
    
    if (response.code === 200) {
      const appDetail = response.data
      
      // 显示应用详情弹窗
      ElMessageBox.alert(
        `
        <div style="text-align: left; line-height: 1.6;">
          <h3 style="margin-bottom: 15px; color: #409EFF;">${appDetail.appName}</h3>
          <p><strong>应用描述：</strong>${appDetail.appDescription || '暂无描述'}</p>
          <p><strong>应用用户：</strong>${appDetail.appUser || '暂无信息'}</p>
          <p><strong>应用类型：</strong>${appDetail.appType || '其他服务'}</p>
          <p><strong>API密钥：</strong>${appDetail.apiKey || '未设置'}</p>
          <p><strong>密钥：</strong>${appDetail.secretKey || '未设置'}</p>
          <p><strong>应用状态：</strong>${appDetail.appStatus === '0' ? '运行中' : '已停止'}</p>
          <p><strong>创建时间：</strong>${appDetail.createTime || '暂无信息'}</p>
        </div>
        `,
        '应用详情',
        {
          dangerouslyUseHTMLString: true,
          customClass: 'app-detail-dialog',
          confirmButtonText: '关闭'
        }
      )
    } else {
      ElMessage.error('获取应用详情失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取应用详情失败:', error)
    ElMessage.error('获取应用详情失败，请稍后重试')
  }
}

// 删除应用
const deleteApp = async (app) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除应用 "${app.name}" 吗？此操作不可撤销。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 调用删除API
    const response = await appAPI.deleteApp(app.id)
    
    if (response.code === 200) {
      ElMessage.success('应用删除成功')
      // 重新获取应用列表
      await fetchApplications()
    } else {
      ElMessage.error('删除失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除应用失败:', error)
      ElMessage.error('删除应用失败，请稍后重试')
    }
  }
}

// 手动上传
const openManualUpload = (app) => {
  router.push({
    path: '/agriculture/xctl/manual-upload',
    query: { appId: app.id, appName: app.name }
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchApplications()
})
</script>

<style scoped>
.my-applications {
  padding: 20px;
}

.page-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-section {
  padding: 24px;
  margin-bottom: 32px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.search-section-right {
  flex-shrink: 0;
  display: flex;
  gap: 16px;
  align-items: center;
}

.filter-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.search-input-el {
  width: 300px;
}

.btn-create-new {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.btn-create-new:hover {
  background: #2563eb;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #6b7280;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f4f6;
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.applications-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 48px;
  margin-left: 20px;
  margin-right: 20px;
}

.app-card {
  background: linear-gradient(135deg, rgb(244, 244, 246) 20%, #fff 35%, #fff 100%);
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.app-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  /* height: 48px; */ /* 移除固定高度 */
  min-height: 48px; /* 改为最小高度 */
  gap: 16px;
}

.app-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.header-content {
  flex: 1;
  margin-left: 0px;
  min-width: 0;
}

.title-row {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 4px;
  gap: 12px;
}

.status-area {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  color: white;
}

.status-active {
  background: #10b981;
}

.status-inactive {
  background: #ef4444;
}

.tags-row {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
}

.tag-item {
  padding: 3px 8px;
  background: rgb(248,248,250);
  color: rgb(156,154,174);
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
}

.app-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
  line-height: 1.4;
}

.card-description {
  margin: 0;
  margin-bottom: 6px;
  padding: 0 16px;
}

.app-description {
  color: #6b7280;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 16px;
  margin-bottom: 12px;
}

.meta-left {
  flex: 1;
}

.meta-right {
  flex-shrink: 0;
}

.category-label {
  padding: 4px 8px;
  background: rgb(248,248,250);
  color: rgb(156,154,174);
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
}

.update-time {
  font-size: 12px;
  color: #9ca3af;
}

.divider {
  height: 1px;
  background: #e5e7eb;
  margin: 0 16px 16px 16px;
}

.app-actions {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 16px;
  padding: 0 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 8px;
  border-radius: 6px;
}

.action-item:hover {
  background: #f3f4f6;
}

.action-item.action-danger:hover {
  background: #fef2f2;
}

.action-item.action-danger .action-icon {
  color: #ef4444;
}

.action-item.action-danger .action-text {
  color: #ef4444;
}

.action-icon {
  font-size: 18px;
  color: #6b7280;
}

.action-text {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #6b7280;
}

.empty-icon {
  margin-bottom: 24px;
  opacity: 0.5;
}

.empty-state h3 {
  font-size: 24px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 12px;
}

/* 应用详情弹窗自定义样式 */
:deep(.app-detail-dialog) {
  max-width: 600px;
}

:deep(.app-detail-dialog .el-message-box__content) {
  max-height: 500px;
  overflow-y: auto;
}

:deep(.app-detail-dialog .el-message-box__message) {
  font-size: 14px;
  line-height: 1.6;
}

:deep(.app-detail-dialog h3) {
  margin-top: 0;
  margin-bottom: 15px;
  color: #409EFF;
  font-size: 18px;
}

:deep(.app-detail-dialog p) {
  margin: 8px 0;
  word-break: break-all;
}

:deep(.app-detail-dialog strong) {
  color: #333;
  font-weight: 600;
  min-width: 80px;
  display: inline-block;
  margin-bottom: 12px;
}

.empty-state p {
  font-size: 16px;
  margin-bottom: 32px;
}

.btn-create-first {
  padding: 12px 24px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.btn-create-first:hover {
  background: #2563eb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-container {
    max-width: none;
  }
  
  .applications-grid {
    grid-template-columns: 1fr;
  }
  
  .app-actions {
    flex-direction: column;
  }
}
</style>